package handlers

import (
	"backEnd/database"
	"backEnd/models"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// GetWallNewsList 获取壁纸资讯公告列表
func GetWallNewsList(c *gin.Context) {
	startTime := time.Now()

	selectParam := c.Query("select")
	pageNum, _ := strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "9"))
	offset := (pageNum - 1) * pageSize

	var query string
	var args []interface{}

	if selectParam == "true" {
		query = `
			SELECT id, view_count, publish_date, title, author, is_select
			FROM wall_news
			WHERE article_status = 1 AND is_select = 1
			ORDER BY publish_date DESC
		`
	} else {
		query = `
			SELECT id, view_count, publish_date, title, author, is_select
			FROM wall_news
			WHERE article_status = 1
			ORDER BY publish_date DESC
			LIMIT ? OFFSET ?
		`
		args = append(args, pageSize, offset)
	}

	rows, err := database.DB.Query(query, args...)
	if err != nil {
		c.JSON(http.StatusOK, models.Response{
			ErrCode:  400,
			ErrMsg:   "查询失败",
			Data:     nil,
			TimeCost: time.Since(startTime).Milliseconds(),
		})
		return
	}
	defer rows.Close()

	var newsList []models.WallNews
	for rows.Next() {
		var news models.WallNews
		var isSelect int
		err := rows.Scan(&news.ID, &news.ViewCount, &news.PublishDate, &news.Title, &news.Author, &isSelect)
		if err != nil {
			continue
		}
		news.Select = isSelect == 1
		newsList = append(newsList, news)
	}

	c.JSON(http.StatusOK, models.Response{
		ErrCode:  0,
		ErrMsg:   "查询成功",
		Data:     newsList,
		TimeCost: time.Since(startTime).Milliseconds(),
	})
}

// GetWallNewsDetail 获取壁纸资讯公告详情
func GetWallNewsDetail(c *gin.Context) {
	startTime := time.Now()

	newsID := c.Query("id")
	if newsID == "" {
		c.JSON(http.StatusOK, models.Response{
			ErrCode:  400,
			ErrMsg:   "资讯ID不能为空",
			Data:     nil,
			TimeCost: time.Since(startTime).Milliseconds(),
		})
		return
	}

	query := `
		SELECT id, view_count, publish_date, article_status, title, author, content, is_select
		FROM wall_news
		WHERE id = ? AND article_status = 1
	`

	var news models.WallNews
	var isSelect int
	err := database.DB.QueryRow(query, newsID).Scan(
		&news.ID, &news.ViewCount, &news.PublishDate, &news.ArticleStatus, &news.Title, &news.Author, &news.Content, &isSelect,
	)

	if err != nil {
		c.JSON(http.StatusOK, models.Response{
			ErrCode:  400,
			ErrMsg:   "查询失败",
			Data:     nil,
			TimeCost: time.Since(startTime).Milliseconds(),
		})
		return
	}

	news.Select = isSelect == 1

	// 增加阅读次数
	updateQuery := "UPDATE wall_news SET view_count = view_count + 1 WHERE id = ?"
	database.DB.Exec(updateQuery, newsID)

	c.JSON(http.StatusOK, models.Response{
		ErrCode:  0,
		ErrMsg:   "查询成功",
		Data:     news,
		TimeCost: time.Since(startTime).Milliseconds(),
	})
}
